const commonJs = {

    // 防抖
    debounce(fn, wait) {
        let timeout;
        return function () {
            let context = this
            let args = arguments
    
            if (timeout) clearTimeout(timeout)
    
            let callNow = !timeout
            timeout = setTimeout(() => {
                timeout = null
            }, wait)
            if (callNow) fn.apply(context, args)
        }
    },

    /**
     * 防抖升级版
     * @param {*} fn 函数
     * @param {*} wait 等待时间
     * @param {*} immediate 是否立即执行
     * @returns 
     */
    debouncePlus(fn, wait, immediate=false) {
        
        let timer, startTimeStamp=0
        let context, args

        let run = (timerInterval) => {

            timer = setTimeout(() => {

                let now = (new Date()).getTime()
                let interval = now - startTimeStamp

                if (interval < timerInterval) {
                    
                    startTimeStamp = now
                    run (wait - interval)

                } else {

                    if (!immediate) {
                        fn.apply(context, args)
                    }

                    clearTimeout(timer)
                    timer = null
                }
                
            }, timerInterval)
        }

        return function() {
            
            context = this
            args = arguments
            let now = (new Date()).getTime()
            startTimeStamp = now

            if (!timer) {
                if (immeidate) {
                    fn.apply(context, args)
                }
                run(wait)
            }
        }
    },

    // 节流
    throttle(fn, wait) {
        let timeout
        return function() {
            let context = this
            let args = arguments
            if (!timeout) {
                timeout = setTimeout(() => {
                   timeout = null
                   fn.apply(context, args) 
                }, wait)
            }
        }
    },

    /**
     * 节流升级版
     * @param {*} fn 函数
     * @param {*} wait 等待时间
     * @param {*} immediate 是否立即执行
     * @returns 
     */
    throttlePlus(fn, wait, immediate=false) {


        console.log('throttle begin...');

        let timer, context, args

        let run = () => {

            timer = setTimeout(() => {
                
                if (!immediate) {
                    fn.apply(context, args)
                }

                clearTimeout(timer)
                timer = null

            }, wait);
        }

        return function() {
            
            context = this
            args = arguments

            if (!timer) {
                if (immediate) {
                    fn.apply(context, args)
                }
                run()
            }
        }
    },
}

export default commonJs